package com.lm.selenium.service.impl;


import com.lm.selenium.service.ProxyService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

@Service
public class ProxyServiceImpl implements ProxyService {


    // 所有代理池（从配置或外部服务加载）
    private final List<String> allProxies = new CopyOnWriteArrayList<>();

    // 当前可用代理池
    private final Set<String> availableProxies = ConcurrentHashMap.newKeySet();

    private final Random random = new Random();

    public ProxyServiceImpl() {
        // 启动时初始化
        refreshPool();
    }

    @Override
    public boolean hasAvailableProxy() {
        return !availableProxies.isEmpty();
    }

    @Override
    public String getRandomProxy() {
        if (availableProxies.isEmpty()) return null;
        int index = random.nextInt(availableProxies.size());
        return new ArrayList<>(availableProxies).get(index);
    }

    @Override
    public void markFailed(String proxy) {
        availableProxies.remove(proxy);
        System.out.println("代理失效已移除：" + proxy);
    }

    @Override
    public void refreshPool() {
        // 模拟从文件、数据库、远程接口获取代理
        allProxies.clear();
        allProxies.addAll(Arrays.asList(
                "123.45.67.89:8080",
                "98.76.54.32:3128",
                "111.222.333.444:8000"
        ));

        availableProxies.clear();
        availableProxies.addAll(allProxies);

        System.out.println("代理池已刷新，共 " + availableProxies.size() + " 个代理");
    }

    @Override
    public int getAvailableCount() {
        return allProxies.size();
    }
}
